package com.ray.test.serializable;

import com.ray.test.proxy.MockData;
import com.ray.test.proxy.MockTestConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FileCopyUtils;

import java.io.*;

/**
 * @author bo shen
 * @Description: protostuff 序列化
 * @Class: ProtostuffSerializable
 * @Package com.ray.test.serializable
 * @date 2019/12/20 8:50
 * @company <p>杭州传化陆鲸科技有限公司</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
public class JDKSerializable implements Serializable {
    /**
     * 文件后缀
     **/
    private String fileType = ".jdkmock";
    @Override
    public void set(MockTestConfig config) {
        MockData mockData = config.getMockData();
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(config);
            log.info("文件保存地址:{}", config.getSourcePath()+fileType);
            File file = new File(config.getSourcePath()+fileType);
            if (file.exists()) {
                file.delete();
            }
            File fileParent = file.getParentFile();
            //首先创建父类文件夹
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            file.createNewFile();
            FileCopyUtils.copy(bos.toByteArray(), file);
        } catch (IOException e) {
            log.info("文件保存失败", e);
        }
    }

    @Override
    public MockTestConfig get(MockTestConfig config) {
        try {
            File file = new File(config.getFilePath()+fileType);
            if (!file.exists()) {
                return config;
            }
            byte[] data = FileCopyUtils.copyToByteArray(file);
            ByteArrayInputStream bis = new ByteArrayInputStream(data);
            ObjectInputStream ois = new ObjectInputStream(bis);
            MockData mockData = (MockData)ois.readObject();
            config.setHasData(true);
            config.setReflush(false);
            config.setMockData(mockData);
        } catch (Exception e) {
            log.info("文件读取失败", e);
        }
        return config;
    }

    @Override
    public void deleteFile(MockTestConfig config) {
        log.info("文件删除地址:{}", config.getSourcePath() + fileType);
        File file = new File(config.getSourcePath() + fileType);
        if (file.exists()) {
            file.delete();
        }
    }
}
